package com.kt.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kt.mapper.OverallMetricsMapper;
import com.kt.mapper.ProductSalesMapper;
import com.kt.mapper.StoreSalesMapper;
import com.kt.model.OverallMetrics;
import com.kt.model.ProductSales;
import com.kt.model.StoreSales;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StoreSalesService extends ServiceImpl<StoreSalesMapper, StoreSales> {
    @Resource
    private StoreSalesMapper storeSalesMapper;
    @Resource
    private ProductSalesMapper productSalesMapper;
    @Resource
    private OverallMetricsMapper overallMetricsMapper;

    /**
     * 获取门店销售数据（含完成率、同比计算）
     */
    public List<StoreSales> getStoreSalesWithMetrics() {
        // 查询所有门店数据
        List<StoreSales> storeSalesList = storeSalesMapper.selectList(null);

        // 计算完成率和同比
        return storeSalesList.stream().map(store -> {
            // 计算完成率：(实际销售额/目标销售额)*100%
            double completionRate = store.getActualSales().divide(
                    store.getTargetSales(), 4, BigDecimal.ROUND_HALF_UP
            ).doubleValue() * 100;
            store.setCompletionRate(String.format("%.1f%%", completionRate));

            // 计算同比：(今年销售额-去年同期)/去年同期*100%
            if (store.getLastYearSales() != null && store.getLastYearSales().doubleValue() > 0) {
                double yearOnYear = store.getActualSales().subtract(store.getLastYearSales())
                        .divide(store.getLastYearSales(), 4, BigDecimal.ROUND_HALF_UP)
                        .doubleValue() * 100;
                store.setYearOnYear(String.format("%.1f%%", yearOnYear));
            } else {
                store.setYearOnYear("0.0%");
            }

            return store;
        }).collect(Collectors.toList());
    }

    /**
     * 获取销售额前六的门店（按实际销售额降序）
     */
    public List<StoreSales> getTop6StoresBySales() {
        // 构建查询条件：按实际销售额降序，取前6条
        LambdaQueryWrapper<StoreSales> wrapper = new LambdaQueryWrapper<StoreSales>()
                .orderByDesc(StoreSales::getActualSales)
                .last("LIMIT 6");

        return storeSalesMapper.selectList(wrapper);
    }

    /**
     * 获取产品销售数据（用于图表）
     */
    public List<ProductSales> getProductSalesData() {
        return productSalesMapper.selectList(null);
    }

    /**
     * 获取销售额前六的产品
     */
    public List<ProductSales> getTop6ProductsBySales() {
        return productSalesMapper.selectTop6BySalesAmount();
    }

    /**
     * 获取总体指标（含折扣率、售空率计算）
     */
    public OverallMetrics getOverallMetrics() {
        // 查询最新总体指标
        OverallMetrics metrics = overallMetricsMapper.selectLatest();
        if (metrics == null) {
            return null;
        }

        // 计算折扣率：折扣金额/原价总金额*100%
        double discountRate = metrics.getDiscountAmount().divide(
                metrics.getOriginalTotalPrice(), 4, BigDecimal.ROUND_HALF_UP
        ).doubleValue() * 100;
        metrics.setDiscountRate(String.format("%.1f%%", discountRate));

        // 计算售空率：总销售数量/总库存*100%
        if (metrics.getTotalStock() > 0) {
            double selloutRate = (double) metrics.getTotalSold() / metrics.getTotalStock() * 100;
            metrics.setSelloutRate(String.format("%.1f%%", selloutRate));
        } else {
            metrics.setSelloutRate("0.0%");
        }

        return metrics;
    }
}